from flask import Flask, render_template, request, session, jsonify  # 确保导入了 jsonify
import requests
import json

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于会话加密

@app.route('/')
def index():
    # 检查是否有缓存数据
    if 'data' not in session:
        update_data()
    return render_template('index.html', v4_data=session['v4_data'], v6_data=session['v6_data'])

@app.route('/refresh')
def refresh():
    update_data()
    return jsonify({'status': 'success'})  # 使用 jsonify 返回 JSON 响应

def update_data():
    # 获取数据
    url = "https://api.vvhan.com/tool/cf_ip"
    response = requests.get(url)
    data = response.json()

    # 提取IPv4和IPv6数据
    v4_data = data["data"]["v4"]
    v4_combined = v4_data["CM"] + v4_data["CU"] + v4_data["CT"]
    v6_data = data["data"]["v6"]
    v6_combined = v6_data["CM"] + v6_data["CU"] + v6_data["CT"]

    # 将数据存储在会话中
    session['v4_data'] = v4_combined
    session['v6_data'] = v6_combined

if __name__ == '__main__':
    app.run(debug=True)